#include "common.h"
/*
 * timer.c
 *
 *  Created on: 2020年7月12日
 *      Author: armwind
 */

/**
  * @brief  Configure the TIM IRQ Handler.
  * @param  None
  * @retval None
  */
uint32_t count_num = 0; //这里表示计数值

void TIM_Init(void)
{
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  uint16_t PrescalerValue = 0xffff;

  /* TIM3 clock enable */
  //TIM3挂在APB1总线，所以默认情况下始终为48M
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

  /* Enable the TIM3 gloabal Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Compute the prescaler value */
  //这里把定时器的时钟设置为6K,所以预分频系数为
  PrescalerValue = (uint16_t) (SystemCoreClock  / 6000) - 1;

  /* Time base configuration */
  //这里stm32f042的TIM3为16 位定时器，所以最大能表示65536。这里由于定时器时钟为6K,那么每1S都会增加到6000
  //下面将TIM_Period设置为6000，1S定时器超时
  TIM_TimeBaseStructure.TIM_Period = 6000; //定时器间歇值
  TIM_TimeBaseStructure.TIM_Prescaler = 0;  //定时器时钟分频，这个是在定时器内部分频，会在下面设置
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //这里不分频
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //计算器想上增加，如1,2,3,4,5.............

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Prescaler configuration */
  TIM_PrescalerConfig(TIM3, PrescalerValue, TIM_PSCReloadMode_Immediate);//定时器自动加载

  /* TIM Interrupts enable */
  TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //使能更新中断

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE); //使能定时器
}

